'''
Parses configuration files

@author: Jarek
'''
import logging
import sys
import traceback

class MainProcessor():
    """
        Main processor for all repositories.
        
        Processes all repositories and generates emails.
    """
    
    def __init__(self, settings, repositories, mail_processor, scanner_factory):
        '''
        Creates the processor.
        '''
        self._settings = settings
        self._repositories = repositories
        self._mail_processor = mail_processor
        self._scanner_factory = scanner_factory
        self._processors = []
        
    
    def process_single_configuration(self, configuration, \
                                     superconfiguration=None):
        """
        Processes single configuration including super configuration if available.
        """
        conf = {}
        if superconfiguration is not None:
            conf.update(superconfiguration)
            del conf['repos']
        conf.update(configuration)
        scanner = self._scanner_factory.get_scanner(conf['type'], \
                                                     conf['title'])        
        if 'type' in conf:
            del conf['type']
        scanner.scan_repo(self._processors, conf)
        
    def _process_single_repo_group(self, repository_set):
        """
        Processes single group of repositories.
        Might be single repository or several of them.
        """
        if 'repos' in repository_set:
            for i in repository_set['repos']:
                self.process_single_configuration(i, repository_set)
        else:
            self.process_single_configuration(repository_set, None)

    def parse_and_process(self):
        """
        Parses and processes everything.
        """
        for repository_group in self._repositories:
            try:
                title = repository_group['title']
                send_to_all_in_group = repository_group['send_to_all_in_group'] \
                    if 'send_to_all_in_group' in repository_group else False
                logging.info("Processing :" + title)
                self._processors = []
                self._process_single_repo_group(repository_group)
                total_changes = 0
                for processor in self._processors:
                    total_changes += len(processor.changes)
                if (total_changes != 0):                    
                    self._mail_processor.process_common_mail(title, \
                                        self._processors, send_to_all_in_group)
                    if not send_to_all_in_group:
                        self._mail_processor.process_emails_to_individuals(\
                                            title, self._processors)
                    if not self._settings.DRY_RUN:
                        logging.info("Saving ids " + title)
                        for processor in self._processors:
                            logging.info(" -> File " + \
                                     processor.get_store_filename())
                            if len(processor.changes) != 0:
                                 processor.save_ids()
                    else:
                        logging.info("NOT Saving ids " + title)                    
                        for processor in self._processors:
                            logging.info(" -> File " + \
                                          processor.get_store_filename())
            except:
                sys.stdout.write("Error when processing "  + str(repository_group) + " : " + str(sys.exc_info()[0]))
                traceback.print_exc(file=sys.stdout) 
            logging.info("-" *80)
